package com.jeequan.jeepay.pay.channel.pmipay;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.model.params.pmopay.PmopayNormalMchParams;
import com.jeequan.jeepay.pay.channel.pmopay.payway.PaymobPayoutTokenService;
import com.jeequan.jeepay.pay.model.MchAppConfigContext;
import com.jeequan.jeepay.pay.rqrs.msg.ChannelRetMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * Paymob放款交易订单查询
 */
@Slf4j
@Service
public class PmipayOrderQueryService implements IPmipayOrderQueryService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private PaymobPayoutTokenService paymobPayoutTokenService;


    @Override
    public String getIfCode() {
        return CS.IF_CODE.PMIPAY;
    }

    @Override
    public List<ChannelRetMsg> query(List<PayOrder> payOrders, MchAppConfigContext mchAppConfigContext) throws Exception {
        List<ChannelRetMsg> channelRetMsgList = new ArrayList<>();
        if (payOrders.isEmpty()) {
            return channelRetMsgList;
        }

        PmopayNormalMchParams config = (PmopayNormalMchParams) mchAppConfigContext.getNormalMchParamsByIfCode(CS.IF_CODE.PMOPAY);
        String accessToken = paymobPayoutTokenService.getToken(config);
        StringBuilder sb = new StringBuilder(config.getDomain());
        sb.append("/api/secure/transaction/inquire/");

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Authorization", String.format("Bearer %s", accessToken));

        List<String> transactionsIds = new ArrayList<>();
        payOrders.stream().forEach(payOrder -> {
            transactionsIds.add(payOrder.getChannelOrderNo());
        });
        JSONObject jsonObject = JSONObject.parseObject(payOrders.get(0).getChannelExtra());
        // 判断是否是银行卡交易
        boolean bankTransactions = jsonObject == null ? false : jsonObject.containsKey("bank_transaction_type");

        JSONObject params = new JSONObject();
        params.put("transactions_ids_list", transactionsIds);
        params.put("bank_transactions", bankTransactions);
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(params, headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(sb.toString(), HttpMethod.POST, httpEntity, String.class);
        log.info("响应状态：{}，响应结果：{}", responseEntity.getStatusCodeValue(), responseEntity.getBody());
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            JSONObject data = JSONObject.parseObject(responseEntity.getBody());
            JSONArray result = data.getJSONArray("results");
            if (result.isEmpty()) {
                return channelRetMsgList;
            }
            result.stream().forEach(o -> {
                JSONObject p = (JSONObject) o;
                ChannelRetMsg channelRetMsg = new ChannelRetMsg();
                String statusCode = p.getString("status_code");
                String disbursementStatus = p.getString("disbursement_status");
                String transactionId = p.getString("transaction_id");
                channelRetMsg.setChannelOrderId(transactionId);
                channelRetMsg.setChannelErrCode(statusCode);
                channelRetMsg.setChannelErrMsg(disbursementStatus);

                if ("200".equals(statusCode)) {
                    // 明确支付成功
                    channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
                    channelRetMsgList.add(channelRetMsg);

                } else if ("failed".equals(disbursementStatus)) {
                    // 明确支付失败
                    channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                    channelRetMsgList.add(channelRetMsg);

                } else {
                    log.warn("渠道订单：{} 支付状态查询结果：{} {}", transactionId, statusCode, disbursementStatus);
                }

            });
        }
        return channelRetMsgList;
    }

}
